﻿@page "/parammonitorlist"
@using IotClientApp.Client.Pages.Dialog;
@using IotClientApp.Shared;
@using IotClientApp.Shared.Ext;
@using Microsoft.AspNetCore.SignalR.Client;
@using Newtonsoft.Json;
@inject NavigationManager Navigation
@implements IAsyncDisposable
@inject HttpClient Http
@inject IDialogService DialogService
@*<MudTable @ref="table" Items="@messages" Breakpoint="Breakpoint.Sm" LoadingProgressColor="Color.Info">
    <ToolBarContent>
        <MudText Typo="Typo.h6">Periodic Elements</MudText>
        <MudSpacer />
        <MudTextField T="string" ValueChanged="@(s=>OnSearch(s))" Placeholder="Search" Adornment="Adornment.Start"
                      AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"></MudTextField>
    </ToolBarContent>
    <HeaderContent>
        <MudTh><MudTableSortLabel SortLabel="参数地址" T="DeviceParamModel">参数地址</MudTableSortLabel></MudTh>
        <MudTh><MudTableSortLabel SortLabel="参数名称" T="DeviceParamModel">参数名称</MudTableSortLabel></MudTh>
        <MudTh><MudTableSortLabel SortLabel="值" T="DeviceParamModel">值</MudTableSortLabel></MudTh>
        <MudTh><MudTableSortLabel SortLabel="更新时间" T="DeviceParamModel">更新时间</MudTableSortLabel></MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd DataLabel="参数地址">@context.Address</MudTd>
        <MudTd DataLabel="参数名称">@context.Name</MudTd>
        <MudTd DataLabel="值">@context.Value</MudTd>
        <MudTd DataLabel="更新时间">@context.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")</MudTd>
    </RowTemplate>
    <NoRecordsContent>
        <MudText>No matching records found</MudText>
    </NoRecordsContent>
    <LoadingContent>
        <MudText>Loading...</MudText>
    </LoadingContent>
    <PagerContent>
        <MudPagination SelectedChanged="PageChanged" Count="@pageCount" Class="pa-4" />
    </PagerContent>
</MudTable>*@

<MudGrid>
<MudItem xs="12" md="2">
        <MudList Clickable="true" @bind-SelectedItem="selectedItem" @bind-SelectedValue="selectDeviceId">
            <MudListSubheader>
                设备
                <MudChip Color="Color.Secondary">
                    @(selectedItem?.Text ?? "You are dry") (@(selectDeviceId?.ToString() ?? "0"))
                </MudChip>
            </MudListSubheader>
        @foreach (var Device in Devices)
        {
                <MudListItem Text="@Device.Name" Value="@Device.Id" OnClick="async()=>{
await LoadData();
}" Icon="@Icons.Material.Filled.Drafts"/>
            }
    </MudList>
 </MudItem>
 <MudItem xs="12" md="10">
<MudDataGrid Items="@messages">
    <Columns>
                <PropertyColumn Property="x => x.Name" Title="参数名称" />
                <PropertyColumn Property="x => x.Address" Title="参数地址" />
                <PropertyColumn Property="x => x.Value" Title="值" />
                <PropertyColumn Property="x => x.Timestamp.DateTimeConvertYMDHMS()" Title="更新时间" />
                    
                <TemplateColumn CellClass="d-flex justify-end">
                    <CellTemplate>
                        @if ( context.Item.ReadWrite == "ReadWrite")
                            {
                        <MudStack Row>
                            
                                <MudButton OnClick="()=>{ControlPoint(context.Item.Id);}" Size="@Size.Small" Variant="@Variant.Filled" Color="@Color.Primary">下控</MudButton>
                            
                        </MudStack>
                            }
                    </CellTemplate>
                </TemplateColumn>
    </Columns>
</MudDataGrid>
</MudItem>
</MudGrid>
@code {
    Color _color = Color.Primary;
    private List<DeviceInfoModel> Devices = new List<DeviceInfoModel>();

    MudListItem selectedItem;

    private string selectDeviceName;
    private HubConnection? hubConnection;
    private List<DeviceParamModel> messages = new List<DeviceParamModel>();
    private object selectDeviceId;
    private int pageSize = 20;
    private int pageIndex = 1;
    private int pageCount = 0;
    private string searchString = null;
    protected override async Task OnInitializedAsync()
    {
        await LoadDeviceData();
        if (Devices == null || Devices.Count() == 0)
        {
            return;
        }
        await LoadData();
        hubConnection = new HubConnectionBuilder()
            .WithUrl(Navigation.ToAbsoluteUri("/ParamMonitorHub"))
            .Build();
        hubConnection.On<RealDataModel>("ReceiveRealData", (msg) =>
        {
            if (!messages.Any(t => t.Name == msg.Name))
            {
                return;
            }
            var message = messages.FirstOrDefault(t => t.Name == msg.Name);
            if (message != null && (message.Value != msg.Value || message.Timestamp != msg.Time))
            {
                Console.WriteLine($"{msg.Value} {msg.Time.ToString("yyyy-MM-dd HH:mm:ss")}");
                message.Value = msg.Value;
                message.Timestamp = msg.Time;

                StateHasChanged();
            }
        });

        await hubConnection.StartAsync();
        await Send();
    }
    private async Task LoadDeviceData()
    {
        var response = await Http.PostAsJsonAsync("api/Device/GetDeviceInfos", new GetDeviceInfoModel
        {
        });
        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseContent);
            try
            {
                var result = JsonConvert.DeserializeObject<PageResponse<DeviceInfoModel>>(responseContent);
                if (result != null)
                {
                    if (result.Data.Count() > 0)
                    {
                        selectDeviceId = result.Data.First().Id;
                        selectDeviceName = result.Data.First().Name;
                        Console.WriteLine(selectDeviceName);
                    }
                    Devices = result.Data;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    public bool IsConnected => hubConnection?.State == HubConnectionState.Connected;
    private async Task LoadData()
    {
        var response = await Http.PostAsJsonAsync<GetDeviceParamModel>("api/Param/GetDeviceParams", new GetDeviceParamModel
            {
                DeviceId = selectDeviceId?.ToString()
            });
        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseContent);
            try
            {
                var result = JsonConvert.DeserializeObject<PageResponse<DeviceParamModel>>(responseContent);
                messages = result.Data;
                pageCount = result.PageCount;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        await Send();
    }
    private async Task Send()
    {
        if (hubConnection is not null)
        {
            await hubConnection.SendAsync("SendRealData", selectDeviceId);
        }
    }
    public async ValueTask DisposeAsync()
    {
        if (hubConnection is not null)
        {
            await hubConnection.DisposeAsync();
        }
    }
    private void OnSearch(string text)
    {
        searchString = text;
    }

    private async void ControlPoint(int pointId)
    {
        var parameters = new DialogParameters<PointControl_Dialog> { { x => x.deviceId, selectDeviceId.ToString() }, { x => x.pointId, pointId } };
        var dialog = await DialogService.ShowAsync<PointControl_Dialog>("下控", parameters);
        var result = await dialog.Result;

        if (!result.Canceled)
        {
            Console.WriteLine("ok");
        }
    }
}